<?php
namespace Common\Controller;
use Think\Controller;
//公共基类控制器
class WeibaseController extends Controller{
	//初始化方法
	protected function _initialize(){
		
		//微信用户登录验证
		$code=I('get.code');
		$state=I('get.state');
		if(!empty($code)){
			
			session_unset();
			$appid='wxc68d67067803a88d';
			$appsecret='69f02bd9a8eeffbd9c606c8a99cd3475';
			$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
			$ch=curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			$result=curl_exec($ch);
			echo(curl_error($ch));
//			curl_close($ch);
			
			$hisen=json_decode ($result,TRUE); // 解析json
			if(isset($hisen['access_token'])&!empty($hisen['access_token'])){
				
				$access_token=$hisen['access_token'];
				$openid=$hisen['openid'];
				
				$_SESSION['access_token']=$access_token;
				$_SESSION['openid']=$openid;
				
//				echo $_SESSION['openid'];
//				echo $_SESSION['access_token'];
				
				$url="https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_TIMEOUT, 30);
				$result=curl_exec($ch);
				echo(curl_error($ch));
				curl_close($ch);
				
				$hisen=json_decode ($result,TRUE); // 解析json
				
				$nickname=$hisen['nickname'];
				$sex=$hisen['sex'];
				$city=$hisen['city'];
				$province=$hisen['province'];
				$headimgurl=$hisen['headimgurl'];
				
				$_SESSION['nickname']=$nickname;
				$_SESSION['sex']=$sex;
				$_SESSION['city']=$city;
				$_SESSION['province']=$province;
				$_SESSION['headimgurl']=$headimgurl;
					
//				print_r($hisen);
			}
		}else{
			
			if(empty($_SESSION['openid'])){
				
				$uri=urlencode("http://zzj5150.imwork.net".__ACTION__);
				$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc68d67067803a88d&redirect_uri={$uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
				header("location:{$url}");
//				echo "<br>";
//				echo $uri;
//				echo "<br>";
//				echo $url;
			}
		}
		
		$this->assign('nickname',$_SESSION['nickname']);
		$this->assign('sex',($_SESSION['sex']?"男":"女"));
		$this->assign('city',$_SESSION['city']);
		$this->assign('province',$_SESSION['province']);
		$this->assign('headimgurl',$_SESSION['headimgurl']);
	}
}